package com.kaihui.lib_base.utils

import android.content.Context
import android.content.Intent
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Response


class DownloadService {

    private val client = OkHttpClient()

    suspend fun downloadFile(context:Context,url: String, filePath: String) {
        withContext(Dispatchers.IO) {
            val request = Request.Builder().url(url).build()
            val response = client.newCall(request).execute()
            if (response.isSuccessful) {
                val responseBody = response.body
                if (responseBody != null) {
                    val file = File(filePath)
                    val outputStream = FileOutputStream(file)
                    outputStream.use { output ->
                        responseBody.byteStream().use { input ->
                            input.copyTo(output)
                        }
                    }
                    // 发送下载完成广播
                    sendDownloadCompleteBroadcast(context,filePath)
                }
            } else {
                // 处理下载失败
                handleDownloadError(response)
            }
        }
    }

    private fun sendDownloadCompleteBroadcast(context:Context,filePath: String) {
        LogUtil.e("DownloadService----filePath:${filePath}")
        val intent = Intent("com.example.DOWNLOAD_COMPLETE")
        intent.putExtra("filePath", filePath)
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
    }

    private fun handleDownloadError(response: Response) {
        // 错误处理逻辑
    }
}